package com.songcha.library_base.mvvm.base

import android.os.Bundle
import android.view.View
import androidx.databinding.ViewDataBinding
import com.songcha.library_base.interfaces.ILoadMoreData
import com.songcha.library_base.interfaces.IRefreshData


abstract class BaseRefreshLoadMoreMvvmActivity<VM:BaseRefreshLoadMoreViewModel<out BaseRepository,out Any>,DB:ViewDataBinding>:BaseRefreshMvvmActivity<VM,DB> (),
    IRefreshData, ILoadMoreData {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        srl?.apply{
            setEnableLoadMore(true)
            setOnLoadMoreListener {
                viewModel.onLoadingMore()
                onGetLoadMoreData()
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        viewModel.loadMore_state.observe(this){
            when(it){
                BaseRefreshLoadMoreViewModel.LoadMoreState.LOADINGMORE->onLoadingMore()
                BaseRefreshLoadMoreViewModel.LoadMoreState.LOADMORE_SUCCESS->onLoadMoreSuccess(viewModel.loadMoreStart,viewModel.loadMoreCount)
                BaseRefreshLoadMoreViewModel.LoadMoreState.LOADMORE_ERROR->onLoadMoreError(viewModel.loadMore_error!!)
                BaseRefreshLoadMoreViewModel.LoadMoreState.LOADMORE_NO_NETWORK->onLoadMoreNoNetwork()
                BaseRefreshLoadMoreViewModel.LoadMoreState.LOADMORE_CONNECT_ERROR->onLoadMoreConnectError()
                BaseRefreshLoadMoreViewModel.LoadMoreState.LOADMORE_NO_DATA->onLoadMoreNoData()
                BaseRefreshLoadMoreViewModel.LoadMoreState.LOADMORE_TIMEOUT->onLoadMoreTimeout()
            }
        }

    }

    protected open fun onGetLoadMoreData(){}

    override fun addRlstObserve() {
        viewModel!!.rlst.observe(this){
            if(it!=null && !viewModel.isLoadingMore && it.size>0){
                initListData()
            }
        }

        viewModel!!.rlmlst.observe(this){
            if(it!=null && !viewModel.isLoadingMore && it.size>0){
                initLoadMoreListData()
            }
        }
    }

    protected open fun initLoadMoreListData(){}

    override fun onLoadingMore() {

    }

    override fun onRefreshing() {
        super.onRefreshing()
        srl?.resetNoMoreData()
    }

    override fun onLoadMoreSuccess(start: Int, count: Int) {
        srl?.finishLoadMore(true)
        getListAdapter()?.notifyItemRangeChanged(start,count)
    }

    override fun onLoadMoreError(e: Throwable) {
        srl?.finishLoadMore(false)
    }

    override fun onLoadMoreNoNetwork() {
        srl?.finishLoadMore(false)
    }

    override fun onLoadMoreConnectError() {
        srl?.finishLoadMore(false)
    }

    override fun onLoadMoreNoData() {
        srl?.finishLoadMoreWithNoMoreData()
    }

    override fun onLoadMoreTimeout() {
        srl?.finishLoadMore(false)
    }



}